<template>
  <el-dialog
    v-model="visible"
    title="上传文件"
    width="680px"
    :close-on-click-modal="false"
    @close="handleClose"
    class="knowledge-upload-dialog"
    align-center
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-icon">
          <el-icon :size="28"><UploadFilled /></el-icon>
        </div>
        <div class="header-title">
          <h3>上传文件</h3>
          <p class="header-subtitle">支持批量上传，最多50个文件</p>
        </div>
      </div>
    </template>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="uploading"
    >
      <el-form-item label="选择文件" class="upload-form-item">
        <div class="upload-section">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="50"
            multiple
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="beforeUpload"
            drag
            class="file-uploader"
          >
            <div class="upload-area">
              <div class="upload-icon-wrapper">
                <el-icon class="upload-icon"><UploadFilled /></el-icon>
                <div class="upload-icon-bg"></div>
              </div>
              <div class="upload-text">
                <p class="upload-main-text">将文件拖到此处，或<em>点击上传</em></p>
                <p class="upload-tip-text">支持批量上传，最多50个文件，单个文件不超过 500MB</p>
              </div>
            </div>
          </el-upload>
          <!-- 文件列表 -->
          <transition name="file-list">
            <div v-if="fileList.length > 0" class="upload-file-list">
              <div class="file-list-header">
                <span class="file-count">已选择 {{ fileList.length }} 个文件</span>
                <el-button
                  text
                  size="small"
                  @click="clearAllFiles"
                  v-if="fileList.length > 0"
                >
                  <el-icon><Delete /></el-icon>
                  清空
                </el-button>
              </div>
              <div class="file-list-content">
                <div
                  v-for="(file, index) in fileList"
                  :key="index"
                  class="upload-file-item"
                >
                  <div class="file-item-info">
                    <div class="file-icon-wrapper">
                      <el-icon class="file-icon"><Document /></el-icon>
                    </div>
                    <div class="file-details">
                      <div class="file-name" :title="file.name">{{ file.name }}</div>
                      <div class="file-meta">
                        <span class="file-size">{{ formatFileSize(file.size) }}</span>
                        <span class="file-status" v-if="uploadProgress[file.name]">
                          <el-icon><Loading /></el-icon>
                          上传中 {{ uploadProgress[file.name] }}%
                        </span>
                      </div>
                    </div>
                  </div>
                  <el-button
                    text
                    type="danger"
                    size="small"
                    @click="removeFile(index)"
                    class="remove-btn"
                    :disabled="uploading"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </transition>
        </div>
      </el-form-item>

      <el-form-item label="文件标题" prop="title" v-if="fileList.length <= 1">
        <el-input
          v-model="formData.title"
          placeholder="请输入文件标题（默认使用文件名）"
          clearable
        />
      </el-form-item>
      <el-form-item v-else>
        <div class="batch-upload-tip">
          <el-icon><InfoFilled /></el-icon>
          <span>批量上传时，每个文件将使用其文件名作为标题</span>
        </div>
      </el-form-item>

      <el-form-item label="文件描述">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入文件描述（可选）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="所属文件夹">
        <el-tree-select
          v-model="formData.folder_id"
          :data="folderTree"
          :props="{ label: 'name', value: 'id', children: 'children' }"
          placeholder="选择文件夹（可选）"
          clearable
          check-strictly
          :render-after-expand="false"
        />
      </el-form-item>

      <el-form-item label="标签">
        <el-select
          v-model="formData.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="选择或输入标签（可选）"
          style="width: 100%"
        >
          <el-option
            v-for="tag in tagOptions"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="权限设置">
        <div class="permission-group">
          <el-radio-group v-model="formData.permission" class="permission-radio-group">
            <el-radio-button label="public" class="permission-option">
              <div class="permission-content">
                <el-icon class="permission-icon public"><Unlock /></el-icon>
                <div class="permission-info">
                  <div class="permission-name">公开</div>
                  <div class="permission-desc">所有人可见</div>
                </div>
              </div>
            </el-radio-button>
            <el-radio-button label="team" class="permission-option">
              <div class="permission-content">
                <el-icon class="permission-icon team"><User /></el-icon>
                <div class="permission-info">
                  <div class="permission-name">团队</div>
                  <div class="permission-desc">团队成员可见</div>
                </div>
              </div>
            </el-radio-button>
            <el-radio-button label="private" class="permission-option">
              <div class="permission-content">
                <el-icon class="permission-icon private"><Lock /></el-icon>
                <div class="permission-info">
                  <div class="permission-name">私有</div>
                  <div class="permission-desc">仅自己可见</div>
                </div>
              </div>
            </el-radio-button>
          </el-radio-group>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" @click="handleClose" :disabled="uploading">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
        <el-button 
          type="primary" 
          size="large" 
          @click="handleUpload" 
          :loading="uploading"
          class="upload-button"
          :disabled="fileList.length === 0"
        >
          <el-icon v-if="!uploading"><Upload /></el-icon>
          {{ uploading ? '上传中...' : (fileList.length > 1 ? `上传 ${fileList.length} 个文件` : '上传文件') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type UploadInstance, type UploadFile } from 'element-plus'
import { Upload, UploadFilled, Document, Delete, InfoFilled, Loading, Lock, Unlock, User, Close } from '@element-plus/icons-vue'
import { formatFileSize } from '@/utils/common'
import { uploadKnowledgeFile, getKnowledgeFolders, type KnowledgeFile, type KnowledgeFolder } from '@/api/knowledge'
import { ResponseParser } from '@/utils/responseParser'

interface Props {
  modelValue: boolean
  defaultFolderId?: string
  folderTree?: KnowledgeFolder[]
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'uploaded', file: KnowledgeFile): void
  (e: 'batch-uploaded', files: KnowledgeFile[]): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const formRef = ref<FormInstance>()
const uploadRef = ref<UploadInstance>()
const uploading = ref(false)
const uploadProgress = ref<{ [key: string]: number }>({})

const fileList = ref<File[]>([])

const formData = reactive({
  title: '',
  description: '',
  folder_id: props.defaultFolderId || '',
  tags: [] as string[],
  permission: 'private' as 'public' | 'team' | 'private'
})

const folderTree = ref<KnowledgeFolder[]>(props.folderTree || [])
const tagOptions = ref<string[]>([])

const formRules = {
  title: [
    { required: true, message: '请输入文件标题', trigger: 'blur' },
    { min: 1, max: 200, message: '文件标题长度在 1 到 200 个字符', trigger: 'blur' }
  ]
}

// 验证文件夹是否存在
const validateFolderExists = (folderId: string, folders: KnowledgeFolder[]): boolean => {
  if (!folderId) return true // 空文件夹ID表示根目录，总是有效
  
  const findFolder = (id: string, folderList: KnowledgeFolder[]): boolean => {
    for (const folder of folderList) {
      if (folder.id === id) {
        return true
      }
      if (folder.children && folder.children.length > 0) {
        if (findFolder(id, folder.children)) {
          return true
        }
      }
    }
    return false
  }
  
  return findFolder(folderId, folders)
}

// 加载文件夹树
const loadFolderTree = async () => {
  try {
    const response = await getKnowledgeFolders({ tree: true })
    const parsed = ResponseParser.parseResponse<KnowledgeFolder[]>(response)
    if (parsed.success && parsed.data) {
      folderTree.value = parsed.data || []
      
      // 验证当前选择的文件夹是否仍然存在
      if (formData.folder_id && !validateFolderExists(formData.folder_id, folderTree.value)) {
        ElMessage.warning('之前选择的文件夹已不存在，已自动清除')
        formData.folder_id = ''
      }
    } else {
      folderTree.value = []
      // 如果加载失败，清除文件夹选择
      if (formData.folder_id) {
        formData.folder_id = ''
      }
    }
  } catch (error) {
    console.error('加载文件夹列表失败:', error)
    folderTree.value = []
    // 如果加载失败，清除文件夹选择
    if (formData.folder_id) {
      formData.folder_id = ''
    }
  }
}

// 文件变化
const handleFileChange = (file: UploadFile, fileList: UploadFile[]) => {
  // 更新文件列表
  const rawFiles = fileList.map(f => f.raw).filter(Boolean) as File[]
  updateFileList(rawFiles)
  
  // 如果是第一个文件且没有标题，自动填充标题
  if (rawFiles.length === 1 && !formData.title) {
    const name = rawFiles[0].name
    const lastDot = name.lastIndexOf('.')
    formData.title = lastDot > 0 ? name.substring(0, lastDot) : name
  }
}

// 更新文件列表
const updateFileList = (files: File[]) => {
  fileList.value = files
}

// 移除文件
const handleFileRemove = (file: UploadFile, fileList: UploadFile[]) => {
  const rawFiles = fileList.map(f => f.raw).filter(Boolean) as File[]
  updateFileList(rawFiles)
}

// 手动移除文件
const removeFile = (index: number) => {
  fileList.value.splice(index, 1)
  // 同步更新 upload 组件的文件列表
  if (uploadRef.value) {
    const uploadFiles = uploadRef.value.fileList
    uploadFiles.splice(index, 1)
  }
}

// 清空所有文件
const clearAllFiles = () => {
  fileList.value = []
  uploadRef.value?.clearFiles()
}

// 上传前验证
const beforeUpload = (file: File) => {
  // 文件大小限制（与后端保持一致，默认100MB，但允许更大）
  const maxSize = 500 * 1024 * 1024 // 500MB
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过 500MB')
    return false
  }
  
  // 检查文件扩展名（可选，后端会再次验证）
  const fileName = file.name.toLowerCase()
  const hasValidExtension = fileName.includes('.')
  if (!hasValidExtension) {
    ElMessage.warning('文件缺少扩展名，可能无法正确识别文件类型')
  }
  
  return false // 阻止自动上传
}

// 上传文件
const handleUpload = async () => {
  // 验证文件
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }
  
  // 验证文件大小
  const maxSize = 500 * 1024 * 1024 // 500MB
  const oversizedFiles = fileList.value.filter(f => f.size > maxSize)
  if (oversizedFiles.length > 0) {
    ElMessage.error(`以下文件超过 500MB 限制：${oversizedFiles.map(f => f.name).join(', ')}`)
    return
  }
  
  // 如果是单个文件，验证标题
  if (fileList.value.length === 1 && !formData.title) {
    ElMessage.warning('请输入文件标题')
    return
  }
  
  if (formData.title && formData.title.trim().length > 200) {
    ElMessage.warning('文件标题不能超过 200 个字符')
    return
  }

  try {
    if (fileList.value.length === 1) {
      await formRef.value?.validate()
    }
    
    uploading.value = true
    uploadProgress.value = {}
    const uploadedFiles: KnowledgeFile[] = []
    const errors: string[] = []

    // 批量上传文件
    for (let i = 0; i < fileList.value.length; i++) {
      const file = fileList.value[i]
      try {
        // 为每个文件生成标题（如果只有一个文件，使用表单标题；否则使用文件名）
        let fileTitle = formData.title?.trim() || ''
        if (fileList.value.length > 1 || !fileTitle) {
          const name = file.name
          const lastDot = name.lastIndexOf('.')
          fileTitle = lastDot > 0 ? name.substring(0, lastDot) : name
        }

        const formDataToSend = new FormData()
        formDataToSend.append('file', file)
        formDataToSend.append('title', fileTitle)
        if (formData.description && formData.description.trim()) {
          formDataToSend.append('description', formData.description.trim())
        }
        if (formData.folder_id) {
          formDataToSend.append('folder_id', formData.folder_id)
        }
        if (formData.tags.length > 0) {
          formDataToSend.append('tags', formData.tags.join(','))
        }
        formDataToSend.append('permission', formData.permission)
        formDataToSend.append('is_public', String(formData.permission === 'public'))

        uploadProgress.value[file.name] = 50
        const response = await uploadKnowledgeFile(formDataToSend)
        const parsed = ResponseParser.parseResponse<KnowledgeFile>(response)
        
        if (parsed.success && parsed.data) {
          uploadedFiles.push(parsed.data)
          uploadProgress.value[file.name] = 100
        } else {
          errors.push(`${file.name}: ${parsed.message || '上传失败'}`)
        }
      } catch (error: any) {
        let errorMessage = '上传失败'
        if (error?.response?.data?.message) {
          errorMessage = error.response.data.message
        } else if (error?.response?.data?.detail) {
          errorMessage = error.response.data.detail
        } else if (error?.message) {
          errorMessage = error.message
        }
        errors.push(`${file.name}: ${errorMessage}`)
      }
    }

    // 显示上传结果
    if (uploadedFiles.length > 0) {
      if (uploadedFiles.length === 1) {
        ElMessage.success('上传成功')
        emit('uploaded', uploadedFiles[0])
        // 同时触发批量上传事件以保持一致性
        emit('batch-uploaded', uploadedFiles)
      } else {
        ElMessage.success(`成功上传 ${uploadedFiles.length} 个文件`)
        emit('batch-uploaded', uploadedFiles)
      }
      
      if (errors.length > 0) {
        ElMessage.warning(`部分文件上传失败：${errors.join('; ')}`)
      }
      
      handleClose()
    } else {
      ElMessage.error(`上传失败：${errors.join('; ')}`)
      
      // 检查是否是文件夹不存在的错误
      const folderError = errors.find(e => e.includes('文件夹不存在') || e.includes('无效的文件夹ID'))
      if (folderError) {
        formData.folder_id = ''
        await loadFolderTree()
      }
    }
  } catch (error: any) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败，请稍后重试')
  } finally {
    uploading.value = false
    uploadProgress.value = {}
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  fileList.value = []
  formData.title = ''
  formData.description = ''
  formData.folder_id = props.defaultFolderId || ''
  formData.tags = []
  formData.permission = 'private'
  uploadProgress.value = {}
  uploadRef.value?.clearFiles()
  formRef.value?.resetFields()
}

// 监听对话框打开
watch(visible, async (val) => {
  if (val) {
    // 先加载文件夹树
    await loadFolderTree()
    
    // 然后设置默认文件夹（如果提供且存在）
    if (props.defaultFolderId) {
      if (validateFolderExists(props.defaultFolderId, folderTree.value)) {
        formData.folder_id = props.defaultFolderId
      } else {
        ElMessage.warning('默认文件夹不存在，已清除选择')
        formData.folder_id = ''
      }
    }
  }
})

// 监听 defaultFolderId 变化
watch(() => props.defaultFolderId, (val) => {
  if (val) {
    formData.folder_id = val
  }
})
</script>

<style scoped lang="scss">
.knowledge-upload-dialog {
  :deep(.el-dialog__header) {
    padding: 0;
    border-bottom: none;
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }

  :deep(.el-dialog__footer) {
    padding: 20px 24px;
    border-top: 1px solid #e2e8f0;
    background: linear-gradient(to bottom, #f8fafc 0%, #ffffff 100%);
  }

  .dialog-header {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    padding: 24px 24px 20px;
    background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 50%, #8b5cf6 100%);
    color: #fff;
    border-radius: 8px 8px 0 0;
    box-shadow: 0 4px 12px rgba(6, 182, 212, 0.15);

    .header-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 56px;
      height: 56px;
      background: rgba(255, 255, 255, 0.25);
      border-radius: 14px;
      flex-shrink: 0;
      backdrop-filter: blur(10px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .header-title {
      flex: 1;
      min-width: 0;

      h3 {
        margin: 0 0 6px 0;
        font-size: 22px;
        font-weight: 600;
        color: #fff;
      }

      .header-subtitle {
        margin: 0;
        font-size: 13px;
        color: rgba(255, 255, 255, 0.9);
        line-height: 1.5;
      }
    }
  }

  :deep(.el-form) {
    padding: 24px;
    background: #fff;
  }

  :deep(.el-form-item) {
    margin-bottom: 24px;

    .el-form-item__label {
      font-weight: 600;
      color: #1e293b;
      padding-bottom: 8px;
    }
  }

  .upload-form-item {
    margin-bottom: 20px;
  }

  .upload-section {
    width: 100%;

    .file-uploader {
      width: 100%;

      :deep(.el-upload-dragger) {
        width: 100%;
        border: 2px dashed #cbd5e1;
        border-radius: 12px;
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        padding: 40px 20px;

        &:hover {
          border-color: #06b6d4;
          background: linear-gradient(135deg, #ecfeff 0%, #e0f2fe 100%);
          transform: translateY(-2px);
          box-shadow: 0 8px 24px rgba(6, 182, 212, 0.15);
        }

        &.is-dragover {
          border-color: #06b6d4;
          background: linear-gradient(135deg, #cffafe 0%, #bae6fd 100%);
          transform: scale(1.02);
        }
      }

      .upload-area {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 20px;

        .upload-icon-wrapper {
          position: relative;
          width: 80px;
          height: 80px;
          display: flex;
          align-items: center;
          justify-content: center;

          .upload-icon {
            position: relative;
            z-index: 2;
            font-size: 48px;
            color: #06b6d4;
            animation: float 3s ease-in-out infinite;
          }

          .upload-icon-bg {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, rgba(6, 182, 212, 0.1) 0%, rgba(59, 130, 246, 0.1) 100%);
            border-radius: 50%;
            z-index: 1;
          }
        }

        .upload-text {
          text-align: center;

          .upload-main-text {
            margin: 0 0 8px 0;
            font-size: 16px;
            font-weight: 500;
            color: #1e293b;

            em {
              color: #06b6d4;
              font-style: normal;
              font-weight: 600;
            }
          }

          .upload-tip-text {
            margin: 0;
            font-size: 13px;
            color: #64748b;
          }
        }
      }
    }
  }

  @keyframes float {
    0%, 100% {
      transform: translateY(0);
    }
    50% {
      transform: translateY(-10px);
    }
  }

  .upload-file-list {
    margin-top: 16px;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    overflow: hidden;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

    .file-list-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 16px;
      background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
      border-bottom: 1px solid #e2e8f0;

      .file-count {
        font-size: 14px;
        font-weight: 600;
        color: #1e293b;
      }
    }

    .file-list-content {
      max-height: 280px;
      overflow-y: auto;
      padding: 8px;

      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        background: #cbd5e1;
        border-radius: 3px;

        &:hover {
          background: #94a3b8;
        }
      }
    }

    .upload-file-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px;
      border-radius: 8px;
      transition: all 0.2s;
      margin-bottom: 4px;

      &:hover {
        background: #f8fafc;
        transform: translateX(4px);
      }

      &:last-child {
        margin-bottom: 0;
      }

      .file-item-info {
        display: flex;
        align-items: center;
        gap: 12px;
        flex: 1;
        min-width: 0;

        .file-icon-wrapper {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 40px;
          height: 40px;
          background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
          border-radius: 10px;
          flex-shrink: 0;

          .file-icon {
            color: #3b82f6;
            font-size: 20px;
          }
        }

        .file-details {
          flex: 1;
          min-width: 0;

          .file-name {
            font-size: 14px;
            font-weight: 500;
            color: #1e293b;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-bottom: 4px;
          }

          .file-meta {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 12px;
            color: #64748b;

            .file-size {
              flex-shrink: 0;
            }

            .file-status {
              display: flex;
              align-items: center;
              gap: 4px;
              color: #06b6d4;

              .el-icon {
                animation: spin 1s linear infinite;
              }
            }
          }
        }
      }

      .remove-btn {
        flex-shrink: 0;
        opacity: 0.6;
        transition: all 0.2s;

        &:hover {
          opacity: 1;
          transform: scale(1.1);
        }
      }
    }
  }

  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  .file-list-enter-active,
  .file-list-leave-active {
    transition: all 0.3s ease;
  }

  .file-list-enter-from {
    opacity: 0;
    transform: translateY(-10px);
  }

  .file-list-leave-to {
    opacity: 0;
    transform: translateY(-10px);
  }

  .batch-upload-tip {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 14px 16px;
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    border: 1px solid #bae6fd;
    border-radius: 10px;
    color: #0369a1;
    font-size: 13px;
    line-height: 1.5;

    .el-icon {
      font-size: 18px;
      flex-shrink: 0;
    }
  }

  :deep(.el-input__wrapper) {
    border-radius: 8px;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 0 0 1px #06b6d4 inset;
    }

    &.is-focus {
      box-shadow: 0 0 0 2px rgba(6, 182, 212, 0.2);
    }
  }

  :deep(.el-textarea__inner) {
    border-radius: 8px;
    transition: all 0.3s;

    &:hover {
      border-color: #06b6d4;
    }

    &:focus {
      border-color: #06b6d4;
      box-shadow: 0 0 0 2px rgba(6, 182, 212, 0.1);
    }
  }

  :deep(.el-select__wrapper) {
    border-radius: 8px;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 0 0 1px #06b6d4 inset;
    }
  }

  .permission-group {
    width: 100%;

    .permission-radio-group {
      display: flex;
      gap: 12px;
      width: 100%;

      .permission-option {
        flex: 1;
        height: auto;
        padding: 0;
        border-radius: 10px;
        overflow: hidden;

        :deep(.el-radio-button__inner) {
          width: 100%;
          padding: 16px;
          border: 2px solid #e2e8f0;
          border-radius: 10px;
          background: #f8fafc;
          transition: all 0.3s;
          box-shadow: none;

          &:hover {
            border-color: #06b6d4;
            background: #ecfeff;
          }
        }

        :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
          border-color: #06b6d4;
          background: linear-gradient(135deg, #ecfeff 0%, #cffafe 100%);
          color: #0891b2;
          box-shadow: 0 0 0 3px rgba(6, 182, 212, 0.15);
        }

        .permission-content {
          display: flex;
          align-items: center;
          gap: 12px;

          .permission-icon {
            font-size: 24px;
            flex-shrink: 0;

            &.public {
              color: #10b981;
            }

            &.team {
              color: #3b82f6;
            }

            &.private {
              color: #f59e0b;
            }
          }

          .permission-info {
            flex: 1;
            text-align: left;

            .permission-name {
              font-size: 14px;
              font-weight: 600;
              color: inherit;
              margin-bottom: 4px;
            }

            .permission-desc {
              font-size: 12px;
              color: #64748b;
              line-height: 1.4;
            }
          }
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    .upload-button {
      min-width: 140px;
      font-weight: 500;
      background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%);
      border: none;
      transition: all 0.3s;

      &:hover:not(:disabled) {
        background: linear-gradient(135deg, #0891b2 0%, #2563eb 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(6, 182, 212, 0.3);
      }

      &:active:not(:disabled) {
        transform: translateY(0);
      }

      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }
    }
  }
}
</style>

